import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Table, Card} from 'antd';
import TextInput from 'Shared/components/TextInput';
import {PAGE, FIXED_COLUMN_WIDTH, TABLE, PAGINATION_OPTIONS, FORM_OPTIONS, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT} from '../constants';
import {addAssist, updateAssist} from './api';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import routes from './routes';
import Return from '../common/Return';
import DropdownMenu from 'Shared/components/DropdownMenu';
const FormItem = Form.Item;
class RepairMode extends React.PureComponent {
    state = {
        loading: false,
        error: false,
        showPanel: false,
        currentId: '',
    };
    
    handleConditionChange = (value, name) => {
        this.props.onConditionsChange(name, value);
    };

    handleFilterPressEnter = (value, name) => {
        this.props.onConditionsChange(name, value);
        this.props.querySearch();
    }
    handleTableChange = (pagination, filters, sorter) => {
        if(pagination.pageSize)
            this.props.onConditionsChange('pageSize', pagination.pageSize);
        if(pagination.current)
            this.props.onConditionsChange('pageIndex', pagination.current - 1);
        if(sorter.order && sorter.field) {
            this.props.onConditionsChange('sortedColumnKey', sorter.columnKey);
            this.props.onConditionsChange('sortedOrder', sorter.order);
        }
        this.props.querySearch();
    };

    isSortOrder = propName => this.props.sortedColumnKey === propName && this.props.sortedOrder;
    
    onClickEdit = e => {
        const {id} = e.target.dataset;
        this.setState({
            currentId: id,
            showPanel: true
        });
    }

    onClickAdd = () => {
        this.setState({
            currentId: '',
            showPanel: true
        });
    }

    onCancel = () => {
        this.setState({
            currentId: '',
            showPanel: false
        });
    }

    onSubmit = data => {
        const {id, rowVersion, description, code, name, partCategoryId, userDefinedAssistPartDetails} = data;
        if(!id)
            return addAssist({
                code,
                name,
                description,
                partCategoryId,
                userDefinedAssistPartDetails
            }).then(success => {
                this.setState({
                    loading: false,
                });
                if(success) {
                    this.onCancel();
                    this.props.querySearch();
                }
                return success;
            });
        return updateAssist(id, {
            rowVersion,
            description,
            name,
            partCategoryId,
            userDefinedAssistPartDetails
        }).then(success => {
            this.setState({
                loading: false,
            });
            if(success) {
                this.onCancel();
                this.props.querySearch();
            }
            return success;
        });
    }

    onReset = () => {
        this.setState({condition: Object.assign({}, this.state.condition, {
            code: '',
            name: ''
        })});
    }

    render() {
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'repairMode.column.code',
                    defaultMessage: '编号'
                }),
                sorter: true,
                sortOrder: this.isSortOrder('code'),
                dataIndex: 'code'
            }, {
                title: this.props.intl.formatMessage({
                    id: 'repairMode.column.name',
                    defaultMessage: '名称'
                }),
                sorter: true,
                sortOrder: this.isSortOrder('name'),
                dataIndex: 'name'
            }, {
                title: this.props.intl.formatMessage({
                    id: 'repairMode.column.description',
                    defaultMessage: '描述'
                }),
                dataIndex: 'description'
            }
        ];

        const pagination = {
            total: this.props.total,
            current: this.props.pageIndex + 1,
            pageSize: this.props.pageSize,
            ...PAGINATION_OPTIONS
        };
        if(hasPermissions(this.props.permissions, PERMISSION.assistUpdate))
            columns.push({
                title: this.props.intl.formatMessage({
                    id: 'repairMode.column.action',
                    defaultMessage: '操作'
                }),
                dataIndex: 'action',
                width: FIXED_COLUMN_WIDTH,
                fixed: 'right',
                render: (t, r) => {
                    const menus = [
                        {
                            id: 'update',
                            children: (
                                // <a key="update" data-id={r.id} onClick={this.onClickEdit}>
                                <a key="update" data-id={r.id} href={`#${routes.assistUpdate.format(r.id)}`}>
                                    {this.props.intl.formatMessage({
                                        id: 'repairMode.operation.update',
                                        defaultMessage: '编辑'
                                    })}
                                </a>
                            ),
                            hidden: !hasPermissions(r.options, PERMISSION.update)
                        },
                    ];
                    return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                }
            });
        return (
            <div>
                <Card>
                    <Form className="form-standard">
                        <Row>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'repairMode.form.code',
                                        defaultMessage: '编号'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <TextInput
                                        name="code"
                                        value={this.props.conditions.code}
                                        onPressEnter={this.handleFilterPressEnter}
                                        onBlur={this.handleConditionChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'repairMode.form.name',
                                        defaultMessage: '名称'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <TextInput
                                        name="name"
                                        value={this.props.conditions.name}
                                        onPressEnter={this.handleFilterPressEnter}
                                        onBlur={this.handleConditionChange} />
                                </FormItem>
                            </Col>
                        </Row>
                        <Row className="operation-buttons">
                            <Col span={16}>
                                <Button type="primary"
                                    loading={this.state.loading}
                                    onClick={this.props.querySearch}>
                                    {this.props.intl.formatMessage({
                                        id: 'repairMode.query',
                                        defaultMessage: '查询'
                                    })}
                                </Button>
                                <Button key="clear" onClick={this.props.onResetClick}>
                                    {this.props.intl.formatMessage({
                                        id: 'repairMode.btn.reset',
                                        defaultMessage: '重置'
                                    })}
                                </Button>
                            </Col>
                            {hasPermissions(this.props.permissions, PERMISSION.assistAdd)
                                ? <Col span={8} className="col-align-right">
                                    {/* <Button key="add" type="primary" onClick={this.onClickAdd}> */}
                                    <Button key="add" type="primary" href={`#${routes.assistAdd.format()}`}>
                                        {this.props.intl.formatMessage({
                                            id: 'repairMode.btn.add',
                                            defaultMessage: '新增'
                                        })}
                                    </Button>
                                </Col> : null}
                        </Row>
                    </Form>
                </Card>
                <Card>
                    <Table
                        className="white-space-nowrap"
                        rowKey="id"
                        dataSource={this.props.assists}
                        columns={columns}
                        loading={this.state.loading || this.props.loading}
                        pagination={pagination}
                        onChange={this.handleTableChange}
                        {...TABLE}
                        locale={{emptyText: this.state.error ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT}} />
                </Card>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}

RepairMode.propTypes = {
    assists: PropTypes.array.isRequired,
    loading: PropTypes.bool.isRequired,
    conditions: PropTypes.object,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    permissions: PropTypes.array,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};

import {connect} from 'react-redux';

import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableAssistsSearch, saveQueryAssistsCondition, resetQueryAssistsPanel} from './actions';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getAssistsData = selectorFactory(['page', 'domainData', 'assists', 'data']);
const getConditions = selectorFactory(['page', 'appState', 'queryAssistsBySort']);
const mapStateToProps = state => ({
    conditions: getConditions(state),
    permissions: getPermissions(state),
    assists: getAssistsData(state),
    loading: state.getIn(['page', 'domainData', 'assists', 'isFetching']),
    total: state.getIn(['page', 'domainData', 'assists', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryAssistsBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryAssistsBySort', 'pageSize']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryAssistsBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryAssistsBySort', 'sortedOrder']),
});

const mapDispatchToProps = (dispatch, props) => ({
    onCancel: () => {
        props.history.push(routes.query.url());
    },
    querySearch: () => dispatch(tableAssistsSearch()),
    onConditionsChange: (name, value) => dispatch(saveQueryAssistsCondition(name, value)),
    onResetClick: () => dispatch(resetQueryAssistsPanel()),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(RepairMode));
